import { CategoryModel } from '../../models/CategoryModel.js'
let shopcart = new CategoryModel()
const UTIL = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: false, //默认为false(是否有数据)
    shopcartData: [],//购物车商品数据
    shopping_date: [],//购物车时间
    isAllSelect: true,//全选
    price:0,//总金额
    isSelect:false,//日期下拉
    riqi:'', // 日期
    aWeek:[],
    dateList:[],
  },
  //下拉框
  shopcart_xiala:function(e){
    console.log(e)
    var index = this.data.shopcartData[e.currentTarget.dataset.index];
    index.isSelect = !index.isSelect;

      this.setData({
        shopcartData:this.data.shopcartData
      })
  },
  //组件返回参数
  signEvent: function(e){
    let that = this
    that.data.shopcartData.forEach(v => {
      if(v._id == e.detail.addId){
        if (e.detail.total < 1) {
          v.total = 1
          that.setData({
            shopcartData:that.data.shopcartData
          })
          that.removeOneShopcart([e.detail.addId],e.detail.index)
          return
        }
        v.num = e.detail.total
        that.setData({
          shopcartData:that.data.shopcartData
        })
      }
    });
    let ids = {};
    ids._id = e.detail.addId;
    ids.num = e.detail.total;
    console.log(ids)
    //更新购物车商品
    if (e.detail.total > 1) {
      shopcart.updatedShopcart(ids, data => {
        console.log(data)
      })
    }
    that.sum()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    that.ShoppingCartPsot()
    that.data_time()
  },
  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
    let that = this
    that.onLoad()
  },
  //购物车商品信息
  ShoppingCartPsot() {
    //加载提示
    wx.showLoading({
      title: '加载中...'
    })
    let that = this
    shopcart.getShopcart(res=>{
      wx.hideLoading();
      console.log(res)
      let shopcartData = res.result.data.data

      wx.setStorageSync('carts', shopcartData)

      for(var i =0;i< shopcartData.length;i++){
          if(that.data.isAllSelect == true){
              shopcartData[i].danxuan = true
          }
      }
      if(shopcartData.length > 0) {
          that.setData({
              active: false,
              shopcartData: shopcartData,
          });
          that.sum()
      }else{
        that.setData({
          active: true,
          shopcartData:[]
        });
      }

      // that.data.dateList.length = that.data.shopcartData.length;
      for(var i =0;i< shopcartData.length;i++){
        that.data.dateList.splice(i , 1, shopcartData[i].day);
      }
      that.setData({
        dateList: that.data.dateList,
      })
      console.log(that.data.dateList)

    })

  },
  //单选
  simpleSelect: function (e) {
    console.log(e)
    var index = this.data.shopcartData[e.currentTarget.dataset.index];
    index.danxuan = !index.danxuan;
    if (index) {
      this.setData({
        shopcartData: this.data.shopcartData
      })
    }
    // 遍历所有单选，如果发现一个没有勾选，则表明全选不能勾选
    var isHas = false;
    for (var i = 0; i < this.data.shopcartData.length; i++) {
      if (!this.data.shopcartData[i].danxuan) {
        this.setData({
          isAllSelect: false
        })
        isHas = true;
        break;
      }
    }

    if (!isHas) {
      this.setData({
        isAllSelect: true
      })
    }
    //计算总金额
    this.sum();

  },
  //全选
  allSelect: function () {
    this.setData({
      isAllSelect: !this.data.isAllSelect
    })
    //勾选所有单选
    this.data.shopcartData.forEach(v => {
      v.danxuan = this.data.isAllSelect;
    })
    this.setData({
      shopcartData: this.data.shopcartData
    })
    //计算总金额
    this.sum();
  },

  //计算总金额
  sum: function () {
    //获取勾选的商品计算总金额
    var price = 0;
    this.data.shopcartData.forEach(v => {
      if (v.danxuan) {
        price += v.num * v.price;
      }
    })
    this.setData({
      price: price
    })
  },

  //单个删除购物车商品
  removeOneShopcart: function (ids,index) {
    wx.showModal({
      title: '是否删除选中的商品?',
      content: '',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: async(result) => {
          if (result.confirm) {
            this.removeShopcart(ids, index);
            console.log(ids,index)
          }
      }
    });
  },
  //删除选中的购物车商品
  removeSelectShopcart: function (e) {
    //获取选中购物车id
    var ids = [];
    this.data.shopcartData.forEach(v => {
      if (v.danxuan) {
        ids.push(v._id);
      }
    })
    console.log('ids ==> ', ids);

    if (ids.length == 0) {
      wx.showToast({
        title: '请选择删除的商品',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    wx.showModal({
      title: '是否删除选中的商品?',
      content: '',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: async(result) => {
          if (result.confirm) {
            this.removeShopcart(ids);
          }
      }
    });

  },
  //删除数据库的购物车商品
  removeShopcart: function (ids, index) {
    console.log(ids)
    //ids: 购物车id集合
    if (index !== undefined) {
      //单选删除方法
      this.data.shopcartData.splice(index, 1);

    } else {
      //删除选择的购物车商品
      for (var i = this.data.shopcartData.length - 1; i >= 0; i--) {
        if (this.data.shopcartData[i].danxuan) {
          this.data.shopcartData.splice(i, 1);
        }
      }
    }
    //删除购物车商品
    shopcart.removeShopcart(ids, data => {
      console.log(data)
      if(data.errMsg == "cloud.callFunction:ok"){
        wx.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 1000
        })
      }
    })
    //删除缓存购物车商品
    let carts = wx.getStorageSync('carts') //获取缓存中carts信息
    for (let i = 0; i < ids.length; i++) {
        let hasInfo = this._checkProduct(ids[i], carts)
        if (hasInfo.index != -1) {
            carts.splice(hasInfo.index, 1)  //删除数组某一项
        }
    }
    this.setData({
      shopcartData: this.data.shopcartData
    })
    if(this.data.shopcartData <= 0){
      this.setData({
        active: true
      })
    }
    //计算总金额
    this.sum();
  },

  /*购物车中是否已经存在该商品*/
  _checkProduct(id, arr) {
      let item, result = { index: -1 };
      for (let i = 0; i < arr.length; i++) {
          item = arr[i];
          if (item._id == id) {
              result = {
                  index: i,
                  data: item
              }
              break;
          }
      }
      return result;
  },

  //切换状态
  toggleStatus: function (e) {
    //清除其他选中的，选中点击的
    let res = e.currentTarget.dataset
    this.data.dateList.splice(res.i, 1, res.value);
    // TOOLS.modifyCount(typeData.id,typeData.total,e.currentTarget.dataset.value)
    this.setData({
      shopcartData: this.data.shopcartData,
      dateList: this.data.dateList,
    })
    console.log(this.data.dateList)
  },

  //去结算
  pay:function(){
      //获取选中的购物车id
      var ids = [];
      this.data.shopcartData.forEach(v =>{
        if(v.danxuan){
          ids.push(v._id)
        }
      })
      //如果没有勾选商品，则不做任何事情
      if(ids.length == 0){
        wx.showToast({
          title:'请选择需要购买的商品',
          icon:'none',
          duration:2000
        })
        return;
      }
      console.log('ids =>', ids)
      //携带ids跳转到提交订单页面
      wx.navigateTo({
        url:'../commit/commit?id=' + ids.join('@')
      })
  },

  // 获取未来七天的函数
  data_time:function(){
    var arr = []
    for (let i = 0; i < 5; i++) {
      arr.push(UTIL.dealTime(i))
    }
    console.log(arr)
    arr[0].day = '今天'
    this.setData({
      aWeek: arr            // 赋值给data
    })
   },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  toIndexPage: function () {
    wx.switchTab({
        url: "../category/category"
    });
  },  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.setStorageSync('carts', this.data.shopcartData)
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})